<template>
  <div class="course-detail">
    <van-nav-bar
      title="课程详情"
      left-text="返回"
      left-arrow
      @click-left="router.back()"
    />
    
    <div class="content" v-if="course">
      <div class="course-header">
        <img :src="'https://via.placeholder.com/375x200'" :alt="course.title" class="cover">
        <h2 class="title">{{ course.title }}</h2>
        <div class="price">¥{{ course.price }}</div>
      </div>

      <van-cell-group inset title="课程信息">
        <van-cell title="时长" :value="`${course.duration}分钟`" />
        <van-cell title="分类" :value="course.category" />
        <van-cell title="标签">
          <template #default>
            <van-tag plain type="primary" v-for="tag in course.tags" :key="tag" style="margin-right: 5px;">
              {{ tag }}
            </van-tag>
          </template>
        </van-cell>
      </van-cell-group>

      <van-cell-group inset title="课程简介" style="margin-top: 10px;">
        <van-cell :label="course.description" />
      </van-cell-group>
    </div>

    <div class="bottom-bar">
      <van-button type="primary" block @click="handleFavorite">
        {{ isFavorite ? '取消收藏' : '收藏课程' }}
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showToast } from 'vant';
import { courseApi } from '@/api';
import type { Course } from '@/api/types';

const route = useRoute();
const router = useRouter();
const course = ref<Course | null>(null);
const isFavorite = ref(false);

onMounted(async () => {
  const courseId = parseInt(route.params.id as string);
  try {
    const { data } = await courseApi.getCourseById(courseId);
    course.value = data.data;
  } catch (error) {
    showToast('获取课程信息失败');
  }
});

const handleFavorite = async () => {
  if (!course.value) return;
  try {
    await courseApi.toggleFavorite(course.value.id);
    isFavorite.value = !isFavorite.value;
    showToast(isFavorite.value ? '收藏成功' : '已取消收藏');
  } catch (error) {
    showToast('操作失败');
  }
};
</script>

<style scoped>
.course-detail {
  min-height: 100vh;
  padding-bottom: 50px;
  background: #f7f8f8;
}

.content {
  padding: 15px;
}

.course-header {
  background: #fff;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 8px;
}

.cover {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
}

.title {
  margin: 10px 0;
  font-size: 20px;
}

.price {
  color: #ee0a24;
  font-size: 24px;
  font-weight: bold;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px;
  background: #fff;
  box-shadow: 0 -2px 4px rgba(0,0,0,0.1);
}
</style>
